package com.ciaojian.client.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.core.model.OrderComment;
import com.ciaojian.core.service.OrderCommentService;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;

/**
 * <p>
 * 订单评价表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-08-19
 */
@Service
public class OrderCommentServiceImpl extends OrderCommentService {

    @Override
    public Boolean notCommented(Integer orderId) {
        return baseMapper.notCommented(orderId);
    }

    @Override
    public Page<OrderComment> page(Integer userId, Integer store, Integer type, Integer worker, Integer pageNo, Integer pageSize) {
        return baseMapper.page(new Page<>(pageNo, pageSize), userId, store, type, worker);
    }

    /**
     * 获取最新的 [满意/非常满意]评价
     */
    public IPage<OrderComment> goodComment(int id,
                                           Page<OrderComment> page,
                                           QueryWrapper<OrderComment> wrapper) {
        IPage<OrderComment> list;

        wrapper.eq("store_id", id)
                .in("score", 4, 5)
                //通过时间降序查询
                .orderByDesc("add_time");
        list = this.page(page, wrapper);
        //最新评论无 满意/非常满意
        if (list.getTotal() == 0) {
            for (int i = 3; i > 0; i--) {
                wrapper = new QueryWrapper<>();
                wrapper.eq("store_id", id)
                        .in("score", i)
                        .orderByDesc("add_time");
                list = this.page(page, wrapper);
                if (list.getTotal() != 0) {
                    break;
                }
            }
        }

        return list;
    }

    /**
     * 好评率
     *
     * @param total
     * @return
     */
    public String goodRate(int store, int total) {
        String goodRate;
        if (total != 0) {
            // 条件清空
            QueryWrapper<OrderComment> wrapper = new QueryWrapper<>();
            wrapper.select("COUNT(score) as score")
                    .eq("store_id", store)
                    .in("score", "4", "5");
            OrderComment one = this.getOne(wrapper);
            //好评数
            Integer goodScore = one.getScore();

            DecimalFormat df = new DecimalFormat("0.0");
            goodRate = df.format(((float) goodScore / total) * 10);
        } else {
            //无评价记录，好评率默认为0.0
            goodRate = "0.0";
        }
        return goodRate;
    }
}
